<template>
  <div class="orderManageDetail pb40">
    <div class="ml30 mr30 mt10 row-spaceb-col-center">
      <div class="fs18">订单详情</div>
      <el-button type="primary" @click="goBack" size="medium" plain>返回</el-button>
    </div>
    <div class="main-container">
      <div class="head">订单状态</div>
      <!-- 状态条 -->
      <div class="block">
            <el-steps :active="orderStep" class="mg30 ml80 mr80" align-center>
              <el-step title="申请服务" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=1" src="@/assets/image/order/1_a.svg">
                  <img v-else src="@/assets/image/order/1.svg"> -->
                  <icon-font v-if="orderStep>=0" size="45" color="#436AF7"  class="icon-shenqingfuwu" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-shenqingfuwu" />
                </template>
              </el-step>
              <el-step title="服务商接单" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=2" src="@/assets/image/order/2_a.svg">
                  <img v-else src="@/assets/image/order/2.svg"> -->
                  <icon-font v-if="orderStep>=1 && orderStep!=6" size="45" color="#436AF7"  class="icon-fuwushangjiedan" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-fuwushangjiedan" />
                </template>
              </el-step>
              <el-step title="签订合同" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=3" src="@/assets/image/order/3_a.svg">
                  <img v-else src="@/assets/image/order/3.svg"> -->
                  <icon-font v-if="orderStep>=2 && orderStep!=6" size="45" color="#436AF7"  class="icon-qiandinghetong" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-qiandinghetong" />
                </template>
              </el-step>
              <el-step title="线上支付" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=4" src="@/assets/image/order/4_a.svg">
                  <img v-else src="@/assets/image/order/4.svg"> -->
                  <icon-font v-if="orderStep>=3 && orderStep!=6" size="45" color="#436AF7"  class="icon-xianshangzhifu" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-xianshangzhifu" />
                </template>
              </el-step>
              <el-step title="完成服务" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=5" src="@/assets/image/order/5_a.svg">
                  <img v-else src="@/assets/image/order/5.svg"> -->
                  <icon-font v-if="orderStep>=5 && orderStep!=6" size="45" color="#436AF7"  class="icon-wanchengfuwu" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-wanchengfuwu" />
                </template>
              </el-step>
              <el-step title="评价服务" icon="#">
                <template #icon>
                  <!-- <img v-if="orderStep>=6" src="@/assets/image/order/6_a.svg">
                  <img v-else src="@/assets/image/order/6.svg"> -->
                  <icon-font v-if="orderStep>=7" size="45" color="#436AF7"  class="icon-fuwupingjia" />
                  <icon-font v-else size="45" color="#7686A3" class="icon-fuwupingjia" />
                </template>
              </el-step>
            </el-steps>
      </div>
      <!-- 申请服务企业信息 -->
      <div class="block">
        <div class="">申请服务信息</div>
        <div class="company-name mt15">
          <i class="el-icon-location fs28 mr10 color-primary"></i>
          <span class="fwbold fs18">{{ orderDetail.companyName }}</span>
        </div>
        <div class="address fs14 ml35 mt15 color-grey"> 联系方式：<span class="color-primary">{{ orderDetail.customerPhoneNum }}</span></div>
      </div>
      <!-- 服务产品信息 -->
      <div class="block">
        <div class="">服务产品信息</div>
        <div class="company-name mt15">
          <i class="el-icon-office-building fs28 mr10 color-primary"></i>
          <span class="fwbold fs18">{{ orderDetail?.serviceName }}</span>
        </div>
        <div class="row-start mt10">
          <!-- <img class="projectIcon" src="@/assets/image/product.png"> -->
          <img :src="`/api/public/file/v1/public/get/${orderDetail?.productImg}`" class="projectIcon" style="max-width:100%; max-height:100%; object-fit:contain;" alt="" @error="setDefaultImage">
          <div class="productInfo fs-sm">
            <div class="fwbold fs16">{{ orderDetail?.productName }}</div>
            <div>联系方式：<span class="color-primary">{{ contactPerson }}({{ contactPhoneNum }})</span></div>
            <div>服务商地址：{{ productInfo?.companyAddress }}</div>
            <div>工作时间：{{ workDate(productInfo?.workDate) }} {{ productInfo?.workBeginTime }} ~ {{ productInfo?.workEndTime }}</div>
          </div>
        </div>
        <el-divider class="divider"></el-divider>
        <div class="pay-info-wrap">
          <template v-if="orderDetail.pricingType !== 2">
            <div class="coupon-wrap">
              <div class="pay-info-box">
                <div class="pay-info-item">
                  <span class="label">服务金额：</span>
                  <!-- <span class="value" v-if="orderStep === 0 || orderStep === 1">{{ $priceFormat(voucherDetail.limitOriginalPrice,voucherDetail.upperOriginalPrice) }}</span> -->
                  <span class="value">{{ $priceToThousands(orderDetail.totalPrice)}}</span>
                  <span>元</span>
                </div>
                <div class="pay-info-item">
                  <span class="label">服务券抵扣：</span>
                  <!-- <span class="value color-red" v-if="orderStep === 0 || orderStep === 1">{{ $priceFormat(voucherDetail.limitDiscountPrice,voucherDetail.upperDiscountPrice) }} </span> -->
                  <span class="value color-red">{{$priceToThousands(orderDetail.discountPrice)}}</span>
                  <span>元</span>
                </div>
              </div>
            </div>
            <div class="pay-money">
              <span class="label">实付金额：</span>
              <!-- <span class="value color-red" v-if="orderStep === 0 || orderStep === 1">{{$priceFormat(voucherDetail.limitPrice, voucherDetail.upperPrice) }}</span> -->
              <span class="value color-red">{{$priceToThousands(orderDetail.price)}}</span>
              <span class="unit">元</span>
            </div>
            <div class="pay-money">
                <span class="label">实付大写金额(人民币)：</span>
                <span class="value color-red">{{ chineseMoney }}</span>
            </div>
          </template>
          <template v-else>
            <div class="tr">
              <div class="pay-info-item">
                <span class="label">服务金额：</span>
                <span class="value color-red" v-if="orderDetail.totalPrice > 0">{{ $priceToThousands(orderDetail.totalPrice) }} 元</span>
                <span class="value color-red" v-else>{{ contractForm.contactPrice > 0 ? contractForm.contactPrice + ' 元' : '面议' }}</span>
              </div>
              <div class="pay-info-item mt10">
                <span class="label">服务券补贴：</span>
                <span class="value color-red" v-if="orderDetail.discountPrice > 0">{{$priceToThousands(orderDetail.discountPrice)}} 元</span>
                <span class="value color-red" v-else>{{ contractForm.contactPrice > 0 ? contractForm.discountPrice + ' 元' : (productTypeName?.includes('融资担保') ? '50%' : 'LPR*20%') }}</span>
              </div>
              <div class="pay-info-item mt10">
                <span class="label">实付金额：</span>
                <span class="value color-red" v-if="orderDetail.price > 0">{{$priceToThousands(orderDetail.price)}} 元</span>
                <span class="value color-red" v-else>{{ contractForm.money > 0 ? contractForm.money + ' 元' : '面议' }}</span>
              </div>
            </div>
          </template>
        </div>
      </div>
      <!-- 接单 -->
      <div v-if="orderStep === 0" class="block">
        <div class="row-center mt20">
            <el-button type="primary" @click="cancelOrder" class="button1">取消订单</el-button>
            <el-button type="success" @click="receiveOrder" class="button2 ml20">接单</el-button>
        </div>
      </div>
          <!-- 合同信息 -->
          <div v-if="orderStep >= 1 && orderStep!= 6" class="block">
            <div>合同信息</div>
                <el-alert v-if="orderStep == 1" class="mt10" title="支付定金后即可开始服务，在完成服务时需要支付尾款。" type="warning" :closable="false"> </el-alert>
                <div v-if="orderStep == 1" class="contractMoney">
                    <el-form :model="contractForm" :rules="contractRules" ref="payFormRef" label-width="200px" size="medium"
                      style="margin-top: 12px;">
                      <el-row :gutter="10">
                        <el-col v-if="productTypeName?.includes('设备租赁')" :span="24">
                          <el-form-item  label="当期LPR:" prop="lpr">
                              <span class="fs16 color-red fwbold">{{lpr}} %</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item v-if="orderDetail.pricingType == 2" label="平台销售价:" prop="contactFee">
                            <el-input 
                              :disabled="orderDetail.contractStatus == 1" 
                              v-model="contractForm.contactPrice" 
                              @blur="inputcalculateContractPrice"
                              style="width: 272px;"
                              placeholder="请输入平台销售价"
                            /> 元
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="合同总金额(补贴后金额):" prop="money">
                            <el-input disabled v-model="contractForm.money" style="width: 272px;"/> 元
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="服务合同:" prop="file">
                            <el-button type="primary" :loading="loading" @click="signConstractDialog" class="submit-btn">签署合同</el-button>
                          </el-form-item>
                        </el-col>

                        <el-col :span="24">
                          <el-form-item label="合同定金:" prop="deposit">
                            <el-input disabled v-model="contractForm.deposit" style="width: 272px;" /> 元
                          </el-form-item>
                        </el-col>

                        <el-col :span="24">
                          <el-form-item label="合同尾款:" prop="balancePayment">
                            <el-input disabled v-model="contractForm.balancePayment" style="width: 272px;" /> 元
                          </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="orderDetail.pricingType == 2">
                          <el-form-item>
                            <el-button :disabled="orderDetail?.serviceContractSignStatus == 1" type="primary" style="width: 272px;" @click="confirmPrice">确认服务合同金额</el-button>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                </div>
              <div v-else class="row-start-col-center">
                <div class="tr pl20 pt20">
                  <div v-if="productTypeName?.includes('设备租赁')" class="tc mb10">
                    <div>当期LPR: <span class="fs16 color-red fwbold">{{lpr}}%</span></div>
                  </div>
                  <div v-if="orderDetail.pricingType == 2">{{ orderDetail.orderType == 2 ? '服务金额' : '平台销售价' }}：<span class="fwbold">
                    <el-input disabled v-model="contractForm.contactPrice" style="width: 272px;"/> 元</span>
                  </div>
                  <div class="mt10">{{ orderDetail.orderType == 2 ? '补贴后金额' : '合同总金额(补贴后金额)' }}：<span class="fwbold">
                    <el-input disabled v-model="contractForm.money" style="width: 272px;"/> 元</span>
                  </div> 
                  <div v-if="orderDetail.orderType == 1" class="mt10">合同定金：<span class="fwbold">
                    <el-input disabled v-model="contractForm.deposit" style="width: 272px;"/> 元</span>
                  </div> 
                  <div v-if="orderDetail.orderType == 1" class="mt10">合同尾款：<span class="fwbold">
                    <el-input disabled v-model="contractForm.balancePayment" style="width: 272px;"/> 元</span>
                  </div>
                </div>
                <div class="ml50">
                  <span>服务合同： </span> <el-button type="text" @click="downloadFile"> 查看合同 <i class="el-icon-view"/> </el-button>
                </div>
            </div>
          </div>
      <div v-if="orderDetail.pricingType === 1">
          <!-- 支付信息 -->
          <div v-if="orderStep >= 2 && orderStep!= 6" class="block">
            <div class="">支付信息</div>
              <div class="tip fs-sm color-primary">
                <i class="el-icon-warning color-red mr5"></i>
                支付定金后即可开始服务，在完成服务时需要支付尾款
              </div>
              <div class="pay-list">
                <el-table :data="payTable" stripe empty-text="等待买家支付" style="width: 100%">
                  <el-table-column label="序号" type="index"></el-table-column>
                  <el-table-column label="支付时间" prop="payTime">
                      <template slot-scope="{ row }">
                        {{ formatDate(row.payTime) }}
                      </template>
                  </el-table-column>
                  <el-table-column label="支付金额(元)" prop="fee">
                    <template slot-scope="scope">
                      <div class="color-red">{{ $priceToThousands(scope.row.fee)}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同剩余尾款(元)" prop="balance">
                    <template slot-scope="scope">
                      <div class="color-red">{{ $priceToThousands(scope.row.balance) }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="支付状态">
                    <template slot-scope="scope">
                      <div class="color-green">{{ scope.row.payStatus }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
          </div>
          <!-- 服务过程佐证 -->
          <el-divider class="divider"></el-divider>
          <div v-if="orderStep >= 3" class="block">
            <div>服务过程佐证</div>
            <div class="row-spacea mt10">
                <div class="col-center">
                      <!-- <uploadImage v-if="orderStep == 3" :class="orderStep == 3 ? '': 'disablecss'"  @setCardPic="setImageList1" :limit="1"/>
                      <el-image v-else :src="startServiceFileUrl" :preview-src-list="[startServiceFileUrl]" style="height:148px" alt="" @error="setDefaultImage"></el-image> -->
                      <div v-if="contractFileId1 || orderStep == 3" class="mb15" @click="downloadProofFile(1)">{{contractFileName1}} <i v-if="contractFileName1" class="el-icon-circle-check color-primary mr5"></i></div>
                      <div v-else @click="reviewProofFile(startServiceFileUrl)" class="showMouse color-primary"><i class="el-icon-view"></i>查看文件</div>
                      <upload-file 
                        v-if="orderStep == 3" 
                        :class="orderStep == 3 ? '': 'disablecss'"  
                        :supportType="['jpeg', 'jpg', 'png', 'gif']"
                        @setFileUrl="uploadRespond1($event)"
                      ></upload-file>
                      <div class="mt5">开始服务</div>
                </div>
                  <div v-if="orderStep >= 4" class="col-center">
                        <!-- <uploadImage v-if="orderStep == 4" :class="orderStep == 4 ? '': 'disablecss'"  @setCardPic="setImageList2" :limit="1"/>
                        <el-image v-else :src="inProgressFileUrl" :preview-src-list="[inProgressFileUrl]" style="height:148px" alt="" @error="setDefaultImage"></el-image> -->
                        <div v-if="contractFileId2 || orderStep == 4" class="mb15" @click="downloadProofFile(2)">{{contractFileName2}} <i v-if="contractFileName2" class="el-icon-circle-check color-primary mr5"></i></div>
                        <div v-else @click="reviewProofFile(inProgressFileUrl)" class="showMouse color-primary"><i class="el-icon-view"></i>查看文件</div>
                        <upload-file v-if="orderStep == 4" :class="orderStep == 4 ? '': 'disablecss'"  @setFileUrl="uploadRespond2($event)"  :supportType="['jpeg', 'jpg', 'png', 'gif']"></upload-file>
                        <div class="mt5">服务中</div>
                  </div>
                  <div v-if="orderStep >= 4" class="col-center">
                        <!-- <uploadImage v-if="orderStep == 4" :class="orderStep == 4 ? '': 'disablecss'"  @setCardPic="setImageList3" :limit="1"/>
                        <el-image v-else :src="serviceCompletedFileUrl" :preview-src-list="[serviceCompletedFileUrl]" style="height:148px" alt="" @error="setDefaultImage"></el-image> -->
                        <div v-if="contractFileId3 || orderStep == 4" class="mb15" @click="downloadProofFile(3)">{{contractFileName3}} <i v-if="contractFileName3" class="el-icon-circle-check color-primary mr5"></i></div>
                        <div v-else @click="reviewProofFile(serviceCompletedFileUrl)" class="showMouse color-primary"><i class="el-icon-view"></i>查看文件</div>
                        <upload-file v-if="orderStep == 4" :class="orderStep == 4 ? '': 'disablecss'"  @setFileUrl="uploadRespond3($event)" :supportType="['jpeg', 'jpg', 'png', 'gif']"></upload-file>
                        <div class="mt5">服务完成</div>
                  </div>
            </div>
          </div>
          <!-- 开始服务 -->
          <div v-if="orderStep == 3" class="block tc">
            <el-button type="primary" @click="beginService">开始服务</el-button>
          </div>
          <!-- 完成服务 -->
          <div v-if="orderStep == 4" class="block tc">
            <el-button type="primary" @click="completeService">完成服务</el-button>
          </div>
          <!-- 服务评价 -->
          <div v-if="orderStep > 5 && orderStep!= 6" class="block">
            <div class="">服务评价</div>
            <el-form :model="rateForm" :rules="rateRules" class="mt15" :disabled="orderStep !== 5"
              size="medium">
              <el-form-item v-if="orderStep == 5" label="评价等级综合评分" prop="starNum" label-width="140px">
                <div class="ml20">
                  <el-rate v-model="rateForm.starNum" allow-half show-text text-color="#F62B00"
                    :colors="['#F62B00', '#F62B00', '#F62B00']" :texts="['不满意', '不太满意', '基本满意', '满意', '非常满意']"></el-rate>
                </div>
              </el-form-item>
              <el-form-item label="评价内容:" prop="comment" label-width="90px">
                <el-input type="textarea" :rows="2" placeholder="请输入评价内容，200字以内" v-model="rateForm.comment"
                  :maxlength="200"></el-input>
              </el-form-item>
            </el-form>
          </div>
      </div>
    </div>
    <!-- 需要认证提示 -->
    <el-dialog title="签署合同" :visible.sync="tipVisible" width="800px" custom-class="my-dialog">
        <div class="ml20">
            <div class="row-start-col-center">
                 <div style="width:180px">1. 设置定金范围：</div>
                 <el-input
                    v-model="depositRatio"
                    :disabled="orderDetail?.serviceContractSignStatus == 1"
                    @blur="validateDepositInput"
                    type="number"
                    :min="20"
                    :max="90"
                    style="width: 170px"
                    placeholder="20-90"
                >
                <template #append>%</template>
             </el-input>
             <div class="ml10" style="color:#f0ad4e"><i class="el-icon-warning-outline"></i><span>20%~90%</span></div>
            </div>
            
            <!-- <div class="mt20 row-start-col-center">
              <div style="width:180px">2.服务内容：</div>
              <el-input
                v-model="serviceContent"
                :disabled="orderDetail?.serviceContractSignStatus == 1"
                type="textarea"
                :rows="4"
                style="width: 400px"
                placeholder="请详细描述所需服务的具体内容、执行方式、交付成果及验收标准（例如：服务范围、工作步骤、时间节点、质量要求等）。该内容将作为合同的一部分，构成具有法律效力的服务条款。"
                :maxlength="10000"
                show-word-limit
              >
              </el-input>
            </div> -->

            <div class="mt20 row-start-col-center">
              <div style="width:180px">2. 添加合同的附加条款：</div>
              <el-button type="primary" :disabled="orderDetail.contractStatus == 1 || orderDetail.contractStatus == 2" :loading="loading" class="contractButton" @click="editContract" >编辑</el-button>
            </div>
            <div class="mt20 row-start-col-center">
              <div style="width:180px">3. 在线预览合同：</div>
              <el-button type="primary" :disabled="orderDetail.contractStatus == 1 || orderDetail.contractStatus == 2" :loading="loading" class="contractButton" @click="generateContract" >生成合同</el-button>
              <el-button type="primary" :disabled="orderDetail.contractStatus < 0" plain :loading="loading" style="margin-left:30px" class="contractButton" @click="downloadFile" >查看合同</el-button>
            </div>
            <div class="mt20 row-start-col-center">
              <div style="width:180px">4. 合同条款确认: </div>
              <el-button :disabled="orderDetail.contractStatus != 0" type="primary" :loading="loading" class="contractButton" @click="agreeContract" >同意</el-button>
            </div>
            <div class="mt20 row-start-col-center"><div style="width:180px">5. 确认签署合同：</div>
                <div>
                  <div v-if="!companySealOk || !legalSealOk">
                      <i class="el-icon-warning-outline color-red"></i> 请先前往桂在益企小程序申请企业公章和法人签名章。
                  </div>
                  <div class="mt20">
                    <span v-if="protocolStatus" class="color-primary mr20" >{{orderDetail.serviceContractSignStatus == 0 ? '未签署' : '已签署，待企业签署'}}</span> 
                    <el-button v-else type="primary" class="contractButton" @click="protocolDialogVisible = true">签署合同</el-button>
                    <span v-if="orderDetail.serviceContractSignStatus == 0"> <i class="el-icon-warning-outline color-red"></i>请扫码登录桂在益企小程序，请经办人完成企业刷脸签署合同。</span>
                  </div>
                </div>
            </div>
            <div v-if="orderDetail.serviceContractSignStatus == 0" class="tc mt20">
                <img src="@/assets/image/miniCode.jpg" class="ml30"  alt="face" style="width: 100px;height: 100px;" /> 
            </div>
        </div>
    </el-dialog>
    <el-dialog title="查看合同" :visible.sync="contactAuthVisible" width="80%" custom-class="my-dialog" top="10" :close-on-click-modal="false">
      <div class="tc">
           <iframe v-if="signUrl" :src="signUrl" frameborder="0" width="100%" height="860px"></iframe>
      </div>
    </el-dialog>
    <!-- 需要认证提示 -->
    <el-dialog title="签署合同" :visible.sync="protocolDialogVisible" width="700px" custom-class="my-dialog" :close-on-click-modal="false">
      <div class="pl50 pr50">
           <div class="fs18 fwbold tc">平台交易须知 </div>
           <div class="ti2 mt20">用券主体和服务商有下列行为之一的，自治区工业和信息化厅有权会同有关单位终止服务券产品交易，要求其退回补贴资金，取消涉事企业领券资格和服务商服务资格，并作为不良信用记录纳入服务档案，情节严重的依法追究相关法律责任。</div> 
           <div class="mt10"> (一)转让、赠送和买卖服务券的;</div>
           <div class="mt10"> (二)转让、转包、分包合同的;</div>
           <div class="mt10"> (三)虚假交易、串通套现，例如伪造服务券合同或提高合同金额等方式的;</div>
           <div class="mt10"> (四)用券主体投诉产生较大不良影响的;</div>
           <div class="mt10"> (五)自查报告和审计报告结果严重不相符的;</div>
           <div class="mt10"> (六)不配合监督和检查的。</div>
           <div class="mt10">
              <el-checkbox v-model="checked">
                    <span class="color-grey">已阅读并同意以上管理办法</span>
              </el-checkbox>
           </div>
           <div class="tc mt30">
              <el-button type="primary" size="medium" class="blue-btn" @click="checkAgreeStatus">下一步</el-button>
           </div>
      </div>
    </el-dialog>
    <el-dialog title="请前往小程序制作签章" :visible.sync="signVisible" width="525px" custom-class="my-dialog">
          <div class="row-spaceb pt20 pl50 pr50">
            <div>
                <div style="width: 43px;height: 5px;background: #436AF7;"></div>
                <div class="mt20">需要使用微信扫码</div>
                <div class="mt10"> 登录 <span class="color-primary">广西桂在益企小程序</span></div>
                <div class="mt10">在个人中心页完成 <strong class="color-primary">制作签章 ！</strong></div>
                <div class="mt10">制作签章完成后请刷新当前页面</div>
            </div>
          <div>
            <img src="@/assets/image/miniCode.jpg" class="ml30"  alt="face" style="width: 149px;height: 149px;" />
          </div>
      </div>
      <div style="text-align: right;margin-top: 40px;">
        <el-button type="info" size="medium" @click="signVisible = false">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { cancelOrder,acceptOrder,getOrderDetail,productPrice,downloadContract, getSignStatus,getProofFile,
listPayRecord, startService, finishService,priceToPay,contractAddonEditUrl,generateContract,agreeContract,fen2uppercase,
acceptAgreement,checkAgreement,downloadFile,calculateContractPrice,submitContractPrice} from '@/api/homeApi'
import uploadFile from "@/components/upload/uploadFile";
import uploadImage from "@/components/upload/uploadImage.vue";
import moment from 'moment';
import { regFenToYuan,workDate } from '@/utils/index'
export default {
  components: {
    uploadFile,
    uploadImage
  },
  props: {
    orderStepProp: {
      type: Number,
      default: 0
    },
    orderId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      moment,
      workDate,
      orderStep: 0,
      // 0-待接单 2-待签合同 3-待支付 4-待服务 5-待评价/待完成 6-取消
      smesInfo: {
        name: '广西北投软件股份有限公司',
        person: '张三',
        phone: '18633336666',
        address: '广西南宁市良庆区飞云路8号北投大厦2号楼17层'
      },
      productInfo: {
        serviceInfo: '小微企业智慧产销管理系统',
        companyName: '广西交科集团有限公司',
        companyPhone: '18899998888',
        companyAddress: '广西南宁市西乡塘区新康西路158号',
        workTime: '周一至周五 早8点30分-晚5点30分',
        workBeginTime:'',
        workEndTime:'',
      },
      contractForm: {
        contactPrice: 0,
        money:0,
        file: '',
        deposit:0,
        balancePayment:0,
        discountPrice:0
      },
      contractRules: {
        file: [{ required: true, message: '请上传合同', trigger: 'blur' }]
      },
      payForm: {
        way: '1',
        accountName: '',
        bank: '',
        address: '',
        subbranch: '',
        account: ''
      },
      payRules: {
        way: [{ required: true, message: '请选择账户方式', trigger: 'blur' }],
        accountName: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
        bank: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
        account: [{ required: true, message: '请输入银行账号', trigger: 'blur' }],
        money: [{ required: true, message: '请输入汇款金额', trigger: 'blur' }],
      },
      payTable: [
        { no: 1, payTime: '2024-6-18 12:20:36', money: '2000元', remain: '12000元', stateName: '支付成功' },
        { no: 2, payTime: '2024-7-18 12:20:36', money: '70000元', remain: '5000元', stateName: '支付成功' },
        { no: 3, payTime: '2024-8-18 12:20:36', money: '50000元', remain: '0元', stateName: '全额付齐' },
      ],
      rateForm: {
        starNum: 5,
        comment: '公司收费合理，员工服务态度好，能够把问题在第一时间解决，效率很高。',
        createTime: '2024-12-12 12:22:23'
      },
      rateRules: {
        score: [{ required: true, message: '请选择评分等级', trigger: 'blur' }]
      },
      contractFileName1:'',
      contractFileId1:'',
      contractFileName2:'',
      contractFileId2:'',
      contractFileName3:'',
      contractFileId3:'',
      orderDetail:{},
      loading: false,
      voucherDetail:{
        limitDiscountPrice: 0,
        limitOriginalPrice: 0,
        limitPrice: 0,
        upperDiscountPrice: 0,
        upperOriginalPrice: 0,
        upperPrice: 0,
      },
      confirmPriceObj:{
        discountPrice: 0,
        originalPrice: 0,
        price: 0,
        voucherBalance: 0
      },
      wpsFileUrl: '',
      tipVisible: false,
      chineseMoney:'',
      companySealOk: false,
      legalSealOk: false,
      signUrl: '',
      contactAuthVisible: false,
      uploadFlag: false,
      disabledFlag: false,
      startServiceFileId:'',
      inProgressFileId:'',
      serviceCompletedFileId:'',
      startServiceFileUrl:'',
      inProgressFileUrl:'',
      serviceCompletedFileUrl:'',
      protocolStatus:0,
      protocolDialogVisible: false,
      checked: false,
      agreeLoading:false,
      signVisible:false,
      contactPerson:'',
      contactPhoneNum:'',
      productTypeName:'',
      lpr: '--',
      depositRatio:20,
      // serviceContent: '',
    }
  },
  mounted() {
    this.getOrderDetail()
    this.signStatus()
  },
  watch: {

  },
  methods: {
    validateDepositInput() {
      // 移除非数字字符
      let value = this.depositRatio.toString().replace(/[^\d]/g, '');
      // 限制范围在20-90之间
      if (value !== '') {
        const num = parseInt(value);
        if (num < 20) {
          this.depositRatio = 20;
          this.$message.warning('定金比例不能小于20%');
        } else if (num > 90) {
          this.depositRatio = 90;
          this.$message.warning('定金比例不能大于90%');
        } else {
          this.depositRatio = num;
        }
      }
    },
    inputcalculateContractPrice() {
        if (!this.contractForm.contactPrice) {
          this.$message.warning('请输入平台销售价');
          return;
        }
        // Call your API to calculate contract prices
        calculateContractPrice({ 
          orderId: this.orderId,
          contactFee: this.contractForm.contactPrice * 100 
        }).then(res => {
          if (res.code === 200) {
            this.contractForm.money = regFenToYuan(res.data.price);
            this.contractForm.deposit = regFenToYuan(res.data.deposit);
            this.contractForm.balancePayment = regFenToYuan(res.data.balancePayment);
            this.contractForm.discountPrice = regFenToYuan(res.data.discountPrice);
            if(this.contractForm.discountPrice == 0){
              // 提示当前无剩余优惠额度
              this.$message.warning('当前无剩余优惠额度');
            }
          }
        });
    },
    confirmPrice() {
      if (!this.contractForm.contactPrice) {
        this.$message.warning('请输入平台销售价');
        return;
      }
      this.$confirm('确认当前服务合同金额吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitContractPrice({orderId:this.orderId,contactPrice:this.contractForm.contactPrice * 100 }).then(res=>{
          if(res.code === 200){
            this.$message.success('服务合同金额已确认');
            // 确认金额后重新调用订单详情接口
            this.getOrderDetail()
          }
        })
      }).catch(() => {});
    },
      signStatus() {
        getSignStatus().then(res=>{
          if(res.code === 200){
            this.companySealOk = res.data.companySealOk,
            this.legalSealOk = res.data.legalSealOk
          }
        })
      },
      agreeStatus(){
        checkAgreement({orderId:this.orderId}).then(res => {
          if(res.code == 200) {
              this.protocolStatus = res.data.accepted ? 1 : 0
          }
        })
      },
      signConstractDialog() {
        if(this.protocolStatus === 0){
          this.protocolDialogVisible = true
        } else {
          this.tipVisible = true
        }
      },
      editContract() {
        contractAddonEditUrl({orderId:this.orderId}).then(res=>{
          if(res.code === 200){
            this.wpsFileUrl = res.data
            window.open(this.wpsFileUrl)
          }
        })
      },
      generateContract() {
        this.loading = true
        try {
          generateContract({orderId:this.orderId,depositRatio:this.depositRatio}).then(res=>{
            if(res.code === 200){
              this.$message({
                type: 'success',
                message: '合同生成成功!'
              });
              this.getOrderDetail()
            } else if(res.code === 4008){
              this.$confirm('产品需要补充服务内容，下架产品后补充服务内容再重新申请上架，是否跳转到服务产品管理页？', '提示', {
                confirmButtonText: '前往补充',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 确认后跳转到服务产品管理页
                this.$router.push({name:'服务产品管理'})
              }).catch(() => {
                // 取消则不做任何操作
              });
            }
          }).finally(()=>{
            this.loading = false
          })
        } catch (error) {
          this.$message.error('生成合同失败: ' + (error.message || '未知错误'))
        }
      },
      agreeContract(){
        this.$confirm('选择同意后，不可再修改附加条款，确定同意吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          agreeContract({orderId:this.orderId,accept:true}).then(res=>{
            if(res.code === 200){
              this.$message({
                type: 'success',
                message: '确认成功!'
              });
              this.getOrderDetail()
            }
          }).finally(() => {
                this.loading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消确认'
          });
        });
      },
      checkAgreeStatus() {
        if(this.checked){
          this.agreeLoading = true
          acceptAgreement({orderId:this.orderId}).then(res => {
            if(res.code == 200){
              this.protocolStatus = 1
            }
          })
          .finally(()=>{
            this.protocolDialogVisible = false
            this.tipVisible = true
            this.agreeLoading = false
          })
        }
      },
      downloadProofFile(type) {
        if(this.orderStep == 3 && type == 1){
            this.$message({
              type: 'warning',
              message: '点击开始服务后才可以查看'
            });
            return
        } else if(this.orderStep == 4 && type == 2){
            this.$message({
              type: 'warning',
              message: '点击完成服务后才可以查看'
            });
            return
        } else if(this.orderStep == 4 && type == 3){
            this.$message({
              type: 'warning',
              message: '点击完成服务后才可以查看'
            });
            return
        } else {
          getProofFile({orderId:this.orderId,fileType:type}).then(res=>{
              if(res.code === 200){
                open(process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data.token}`) 
              }
          })
        }
      },
      reviewProofFile(url) {
        open(url)
      },
      setDefaultImage(event) {
          event.target.src = require('@/assets/image/error.jpg');
      },
      formatDate(date) {
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
      },
      goBack() {
        this.$emit('back')
      },
      uploadRespond1({ fileId, fileName }) {
        this.contractFileName1 = fileName
        this.contractFileId1 = fileId
        this.startServiceFileId = fileId
      },
      uploadRespond2({ fileId, fileName }) {
        this.contractFileName2 = fileName
        this.contractFileId2 = fileId
        this.inProgressFileId = fileId
      },
      uploadRespond3({ fileId, fileName }) {
        this.contractFileName3 = fileName
        this.contractFileId3 = fileId
        this.serviceCompletedFileId = fileId
      },
      cancelOrder() {
        this.$confirm('确定取消订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          cancelOrder({orderId:this.orderId}).then(res=>{
            if(res.code === 200){
              this.$message({
                type: 'success',
                message: '取消成功!'
              });
              this.goBack()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消取消'
          });
        });
      },
      receiveOrder() {
        // if(!this.companySealOk || !this.legalSealOk){
        //       this.signVisible = true
        //       return
        // }
        let that = this
        this.$confirm('确定接单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          acceptOrder({orderId:this.orderId}).then(res=>{
            if(res.code === 200){
              this.$message({
                type: 'success',
                message: '接单成功!'
              });
              this.getOrderDetail()
            } else if(res.code === 4008){
              this.$confirm('产品需要补充服务内容，下架产品后补充服务内容再重新申请上架，是否跳转到服务产品管理页？', '提示', {
                confirmButtonText: '前往补充',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 确认后跳转到服务产品管理页
                this.$router.push({name:'服务产品管理'})
              }).catch(() => {
                // 取消则不做任何操作
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消接单'
          });
        });
      },
      // 获得订单详情
      getOrderDetail() {
        getOrderDetail({orderId:this.orderId}).then(res=>{
          if(res.code === 200){
              this.orderDetail = res.data
              this.orderStep = this.orderDetail.status === 6 ? -1 : this.orderDetail.status
              this.productInfo = this.orderDetail.serviceDetail
              this.contactPerson = this.orderDetail?.productDetail?.contactPerson
              this.contactPhoneNum = this.orderDetail?.productDetail?.contactPhoneNum
              this.productTypeName = this.orderDetail?.productDetail?.productTypeName
              this.orderDetail.productImg = res.data?.productImg.includes('|') ? res.data?.productImg.split('|')[0] : res.data?.productImg;
              this.contractForm.contactPrice = regFenToYuan(this.orderDetail.totalPrice);
              this.lpr = regFenToYuan(res.data.voucherDetail?.lpr?.yearOne)
              // this.serviceContent = res.data.serviceContent || '';
              // productPrice({productId:this.orderDetail?.productDetail.productId,voucherId:this.orderDetail?.voucherId}).then(res=>{
              //   this.voucherDetail = res.data
              // })
              fen2uppercase({fee:this.orderDetail.price}).then(res=>{
                if(res.code === 200){
                  this.chineseMoney = res.data
                }
              })
              if(this.orderStep == 1){
                this.agreeStatus()
              }
              if(this.orderStep >= 1){
                priceToPay({orderId:this.orderId}).then(res=>{
                  if(res.code === 200){
                    this.contractForm.money = regFenToYuan(res.data?.contactPrice);
                    this.contractForm.deposit = regFenToYuan(res.data?.deposit);
                    this.contractForm.balancePayment = regFenToYuan(res.data?.balancePayment);
                  } else {
                    this.contractForm.money = 0;
                    this.contractForm.deposit = 0;
                    this.contractForm.balancePayment = 0;
                  }

                })
              }
              if(this.orderStep >= 2){
                listPayRecord({orderId:this.orderId}).then(res=>{
                  this.payTable = res.data
                })
              }
              if(this.orderStep == 4 ||  this.orderStep == 5 || this.orderStep == 7){
                getProofFile({orderId:this.orderId,fileType:1}).then(res=>{
                    if(res.code === 200){
                      this.startServiceFileUrl = process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data?.token}`
                    }
                })
              }
              if(this.orderStep == 5 || this.orderStep == 7){
                getProofFile({orderId:this.orderId,fileType:2}).then(res=>{
                    if(res.code === 200){
                      this.inProgressFileUrl = process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data?.token}`
                    }
                })
                getProofFile({orderId:this.orderId,fileType:3}).then(res=>{
                    if(res.code === 200){
                      this.serviceCompletedFileUrl = process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data?.token}`
                    }
                })
              }
          }
        })
      },
      // 查看合同
      downloadFile() {
        downloadContract({orderId:this.orderId}).then(res=>{
            if(res.code === 200){
              // this.contactAuthVisible = true
              // this.signUrl = process.env.VUE_APP_FILE_URL+`/public/file/v1/temp/get?token=${res.data.token}`
              open(process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data.token}`)
            }
        })
      },
      // 开始服务
      beginService () {
        if(!this.startServiceFileId){
          this.$message({
            type: 'error',
            message: '请上传开始服务佐证!'
          });
          return
        }
        startService({orderId:this.orderId,startServiceFileId:this.startServiceFileId}).then(res=>{
          if(res.code === 200){
            this.$message({
              type: 'success',
              message: '开始服务成功!'
            });
            this.getOrderDetail()
          }
        })
      },
      // 完成服务
      completeService () {
        if(!this.inProgressFileId || !this.serviceCompletedFileId){
          this.$message({
            type: 'error',
            message: '请上传服务中和服务完成佐证!'
          });
          return
        }
        this.$confirm('确定完成服务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          finishService({orderId:this.orderId,inProgressFileId:this.inProgressFileId,serviceCompletedFileId:this.serviceCompletedFileId}).then(res=>{
            if(res.code === 200){
              this.$message({
                type: 'success',
                message: '完成服务成功!'
              });
              this.getOrderDetail()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消完成服务'
          });
        });
      },
      setImageList1(files) {
        this.startServiceFileId = files[0]
      },
      setImageList2(files) {
        this.inProgressFileId = files[0]
      },
      setImageList3(files) {
        this.serviceCompletedFileId = files[0]
      }
    }
  }
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";
.disablecss {
  pointer-events: none;
  opacity: 0.5;
}
:deep(.el-input.is-disabled .el-input__inner){
  color: $--color-danger;
}
:deep(.el-step__title.is-success) {
  color: $text-color;
}

:deep(.el-step__head.is-success) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__title.is-process) {
  color: $text-color-blue !important;
}

:deep(.el-step__head.is-success .el-step__line-inner) {
  // transition-delay: 0ms;
  border-width: 1px !important;
  width: 100% !important;
}

:deep(.el-step__head.is-process) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__line-inner) {
  // border-style: dashed;
}

:deep(.el-step__title.is-process) {
  font-weight: 400;
  color: rgb(122, 121, 121);
}

:deep(.el-step__title.is-wait) {
  color: rgb(122, 121, 121);
}


:deep(.el-radio.is-bordered.is-checked) {
  border-color: $--color-primary;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: $--color-primary;
  background: $--color-primary;
}

:deep(.el-radio__input.is-checked+.el-radio__label) {
  color: inherit;
}

:deep(.el-radio--medium.is-bordered) {
  padding-top: 8px;
}

:deep(.el-table th.el-table__cell) {
  background: rgb(242, 242, 242);
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background: rgb(242, 242, 242);
}

:deep(.el-rate__icon) {
  font-size: 1.8rem;
}

:deep(.el-rate) {
  height: fit-content;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: inherit;
}

.contractText :deep(.el-input__inner) {
  color: #FF0000;
}


.ml400 {
  margin: 20px 0 20px 400px;
}

.contractButton{
  width: 120px;
  height: 30px;
  padding: 5px;
}

.main-container {
  margin: 12px 30px 30px;
  box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.16);

  .head {
    padding: 10px 22px;
    font-size: 14px;
    background: #F7F8F9;
  }

  .block {
    position: relative;
    padding: 30px;

    &+.block {
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 30px;
        right: 30px;
        display: block;
        height: 1px;
        background-color: #e8e8e8;
      }
    }


    .company-name {
      display: flex;
      align-items: baseline;
    }

    .projectIcon {
      width: 175px;
      height: 111px;
      border-radius: 5px;
    }

    .productInfo {
      margin-left: 30px;

      div+div {
        margin-top: 14px;
      }
    }

    .divider {
      width: 100%;
      margin: 30px auto 30px auto;
    }


    .pay-info-wrap {
      .coupon-wrap {
        margin-top: 17px;
        display: flex;

        .coupon-box {
          position: relative;
          width: 398px;
          height: 82px;
          background: url('~@/assets/image/coupon_bg2.png') no-repeat;
          background-size: auto 100%;
          padding-left: 70px;
          overflow: hidden;

          .year {
            position: absolute;
            top: -12px;
            left: 0;
            font-size: 24px;
            color: #fff;
            font-family: fangsong;
            letter-spacing: 0px;
          }

          .coupon-money {
            margin-top: 14px;
            display: flex;
            align-items: baseline;

            .label {
              position: relative;
              padding-left: 10px;
              font-size: 16px;

              &::before {
                content: '';
                position: absolute;
                top: 8px;
                left: 0;
                display: block;
                width: 5px;
                height: 5px;
                border-radius: 50%;
                background: $--color-danger;
              }
            }

            .value {
              width: 200px;
              font-size: 20px;
              font-weight: bold;
              text-align: right;
            }
          }

          .coupon-time {
            margin-top: 14px;
            display: flex;
            align-items: baseline;
          }
        }

        .pay-info-box {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          justify-content: end;

          .pay-info-item {
            margin-top: 10px;
            padding-right: 25px;

            .label {
              display: inline-block;
              min-width: 80px;
              text-align: right;
            }

            .value {
              display: inline-block;
              min-width: 150px;
              text-align: right;
            }
          }
        }
      }

      .pay-money {
        margin-top: 13px;
        padding: 10px 25px;
        min-height: 50px;
        background: #F7F8F9;
        text-align: right;

        .label {
          display: inline-block;
          min-width: 80px;
          text-align: right;
        }

        .value {
          display: inline-block;
          padding-right: 5px;
          min-width: 150px;
          text-align: right;
          font-size: 24px;
          font-weight: bold;
        }
      }
    }

    .contractInput {
      min-width: 200px;
      height: 28px;
      text-align: center;
      line-height: 28px;
      background: rgba(204, 204, 204, 0.2);
      border: 1px solid rgb(187, 187, 187);
      border-radius: 3px;
    }

    .upload-btn {
      border: 1px solid #CFCFCF;
      background: #FFFFFF;
      color: $--color-primary;
      width: 265px;
    }

    .tip {
      margin: 0 0 18px 0;
    }

    .submit-btn-wrap {
      text-align: center;

      .submit-btn {
        min-width: 150px;
      }
    }

    .pay-list {
      margin-top: 30px;
    }
  }
}

.required-mark {
  color: #F56C6C;
  margin-left: 4px;
}

.mt20 {
  margin-top: 20px;
}
</style>
